﻿function init(){
    var calcMarriage = false;

    $("#interestRate").hide();
    $("#divCola").hide();
    $("#divMaritalPortion").hide();
    $("[datePicker]").datepicker({
        changeMonth: true,
        changeYear: true,
        showAnim: "slideDown",
        yearRange: "-80:+30"
       });
	//$("#valuationDate").datepicker( "setDate", new Date());

    $("#userNextButton").click(function () {
	    if (validateSection(validateClient)) {
		    transition("userData", "planData");
	    }
	    return false;
    });
    $("#planNextButton").click(function () {
	    if (validateSection(validatePlanData)) {
		    transition("planData", "valuationData");
	    }
	    return false;
    });
    $("#planPrevButton").click(function () {
        transition("planData", "userData");
        return false;
    });
    $("#planBackButton").click(function () {
        transition("planData", "userData");
        return false;
    });
    $("#valuationNextButton").click(function () {
	    if (validateSection(validateAssumptions)) {
		    if (!calcMarriage) {
			    marriageDialog.dialog("open");
		    } else {
			    transition("valuationData", "marriageData");
		    }
	    }
	    return false;
    });
    $("#valuationBackButton").click(function () {
    	calcMarriage = false;
    	transition("valuationData", "planData");
    	return false;
    });
    $("#marriageNextButton").click(function () {
	    if (validateSection(validateMarriage)) {
		    survivorDialog.dialog("open");
	    }
	    return false;
    });
    $("#marriageBackButton").click(function () {
        transition("marriageData", "valuationData");
        return false;
    });
    $("#survivorshipBackButton").click(function () {
        if (calcMarriage) {
            transition("survivorshipData", "marriageData");
        } else {
            transition("survivorshipData", "valuationData");
        }
        return false;
    });
    $("#survivorshipNextButton").click(function () {
        //if (validateSection(validateClient) && validateSection(validatePlanData) && validateSection(validateAssumptions) && validateSection(validateMarriage) && validateSection(validateSurvivor)) {
    		$("form").submit();
    	//}
    	return false;
    });

    var survivorDialog = $("#survivorDialog").dialog({
    	width: 600,
    	modal: true,
    	autoOpen: false,
    	title: $("#survivorDialog").attr("header"),
    	buttons: {
    		yes: (function () {
    			closeSections();
    			$("#survivorship").val("true");
    			if ($("#genderM").is(":checked")) {
    				$("#survivorGenderF").prop("checked", true);
    			} else {
    				$("#survivorGenderM").prop("checked", true);
    			}
    			transition("marriageData", "survivorshipData");
    			$("#survivorDialog").dialog("close");
    		}),
    		no: (function () {
    			$("#survivorship").val("false");
    			$("#survivorDialog").dialog("close");
    			$("form").submit();
    		})
    	}
    });
    var marriageDialog = $("#marriageDialog").dialog({
        width: 600,
        modal: true,
        autoOpen: false,
        title: $("#marriageDialog").attr("header"),
        buttons: {
            yes: (function () {
                calcMarriage = true;
                $("#calculateMarriage").val("true");
                transition("valuationData", "marriageData");
                $("#marriageDialog").dialog("close");
            }),
            no: (function () {
                $("#calculateMarriage").val("false");
                $("#marriageDialog").dialog("close");
                survivorDialog.dialog("open");
            })
        }
    });
    var mortalityDialog = $("#mortalityDialog").dialog({
        width: 600,
        modal: true,
        autoOpen: false,
        title: $("#mortalityDialog").attr("header"),
        buttons: {
            ok: (function () {
                $("#mortalityDialog").dialog("close");
            })
        }
    });

    $("#mortalityHelp").click(function () {
        mortalityDialog.dialog("open");
        return false;
    });
    $("#marriageInfoLink").click(function () {
        $("#marriageInfo").slideDown();
    });
    $("#survivorInfoLink").click(function() {
        $("#surivorInfo").slideDown();
    });
}

function closeSections() {
    $("#userData").hide();
    $("#planData").hide();
    $("#valuationData").hide();
    $("#marriageData").hide();
    $("#survivorshipData").hide();
}

function transition(current, next) {
    $("#" + current).css("display", "none");
    $("#" + next).css("display", "");
}

function toggleQuestion(question, show) {
    if (show) {
        $("#" + question).slideDown();
    } else {
        $("#" + question).slideUp();
    }
}

function validateClient() {
	var err = "";
	if ($("#Client_FirstName").val() == "") {
		err += "First name is required. \r\n";
	}
	if ($("#Client_LastName").val() == "") {
		err += "Last name is required. \r\n";
	}
	if (!validEmail($("#Client_Email").val()))
	{
		err += "A valid email address is required. \r\n";
	}

	return err;
}

function validatePlanData()
{
	var err = "";
	if ($("#participantFirstName").val() == "") {
		err += "A first name for the participant is required.  It may be a real name or an alias. \r\n";
	}
	if ($("#participantLastName").val() == "") {
		err += "A last name for the participant is required.  It may be a real name or an alias. \r\n";
	}
	if (!$("#genderM").is(":checked") && !$("#genderF").is(":checked")) {
		err += "Participants gender is required. \r\n";
	}
	if (!validDate($("#dob").val()))
	{
		err += "A valid date of birth is required. \r\n";
	}
	if (!validDate($("#doh").val()))
	{
		err += "A valid date of hire is required. \r\n";
	}
	if ($("#dot").val() != "" && !validDate($("#dot").val()))
	{
		err += "Date of termination is not a valid date. \r\n";
	}
	if (!validDate($("#retirementDate").val())) {
		err += "A valid retirement date is required. \r\n";
	}
	if (!validDecimal($("#monthlyBenefit").val())) {
		err += "A monthly benefit must be provided.  Please provide a valid dollar amount (up to 2 decimal places). \r\n";
	}
	if (!validDate($("#earnedDate").val())) {
		err += "A valid date through which benefit was earned is required. \r\n";
	}
	return err;
}

function validateAssumptions() {
	var err = "";
	if ($("#colaTrue").is(":checked") && (($("#cola").val() != "?") && isNaN($("#cola").val()))) {
		err += "A cost of living adjustment must be provided.  Please provide a valid percentage for cost of living, or specify that the benefit is not subject to cost of living increases.  Please enter only numeric values. \r\n";
	}
	return err;
}

function validateMarriage() {
    var err = "";
    if ($("#calcMarriage").is(":checked")) {
        if ($("#fractionalFalse").is(":checked") && (!parseFloat($("#maritalPortion").val()))) {
            err += "A valid marital portion must be provided.  Please provide a valid percentage for the marital portion. \r\n";
        }
        if (!validDate($("#marriageDate").val())) {
            err += "A valid marriage date is required. \r\n";
        }
        if (!validDate($("#marriageEarningStart").val())) {
            err += "A valid start date for earning of benefit must be provided. \r\n";
        }
        if (!validDate($("#marriageEarningEnd").val())) {
            err += "A valid end date for earning of benefit must be provided. \r\n";
        }
    }
	return err;
}

function validateSurvivor() {
    var err = "";
    if ($("#survivor").is(":checked")) {
        if ($("#survivorLastName").val() == "") {
            err += "A survivor last name must be provided.  It may be a real name or an alias. \r\n";
        }
        if (!validDate($("#survivorDob").val())) {
            err += "A valid survivor date of birth is required. \r\n";
        }
        if (!parseFloat($("#survivorPercentage").val())) {
            err += "A valid survivor percentage must be entered. \r\n";
        }
    }
	return err;
}

function validateSection(callback) {
	var err = callback();
	if (err != "") {
		alert(err);
		return false;
	}
	return true;
}

function validEmail(email) {
	var re = /^[a-z0-9!#$%&'*+\/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+\/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
	return email != "" && re.test(email);
}

function validDate(value) {
	var userFormat = 'mm/dd/yyyy';
	var delimiter = /[^mdy]/.exec(userFormat)[0];
	var theFormat = userFormat.split(delimiter);
	var theDate = value.split(delimiter);

	var isDate = function (date, format) {
		var m, d, y;
		for (var i = 0, len = format.length; i < len; i++) {
			if (/m/.test(format[i])) {
				m = date[i];
			}
			if (/d/.test(format[i])) {
				d = date[i];
			}
			if (/y/.test(format[i])) {
				y = date[i];
			}
		}
		return ((m > 0 && m < 13) && (y && y.length == 4) && (d > 0 && d <= new Date(y, m, 0).getDate()));
	};
	return isDate(theDate, theFormat);
}

function validDecimal(value) {
	var re = /^\d+(.(\d{2}))?/;
	return re.test(value);
}